package com.ess.project.examine.personnel.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ess.common.constant.UserConstants;
import com.ess.common.exception.BusinessException;
import com.ess.common.utils.StringUtils;
import com.ess.common.utils.security.ShiroUtils;
import com.ess.common.utils.text.Convert;
import com.ess.project.examine.record.util.ExcelUtil;
import com.ess.project.examine.personnel.domain.ExaminePersonnelEntity;
import com.ess.project.examine.personnel.mapper.PersonnelMapper;
import com.ess.project.system.user.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @Description:
 * @Date: Created in 11:34 上午 2021/3/17
 * @Author: daihui
 * @Modified By:
 */
@Slf4j
@Service
public class PersonnelServiceImpl extends ServiceImpl<PersonnelMapper, ExaminePersonnelEntity> implements IPersonnelService {

    @Autowired
    private PersonnelMapper personnelMapper;

    @Override
    public List<ExaminePersonnelEntity> selectPersonnelList(ExaminePersonnelEntity personnel) {
        QueryWrapper<ExaminePersonnelEntity> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(personnel.getPersonnelCategory())) {
            wrapper.eq("personnel_category", personnel.getPersonnelCategory());
        }
        if (StrUtil.isNotEmpty(personnel.getExamPersonnel())) {
            wrapper.like("exam_personnel", personnel.getExamPersonnel());
        }
        if (null != personnel.getAttend()) {
            wrapper.eq("attend", personnel.getAttend());
        }
        return personnelMapper.selectList(wrapper);
    }

    @Override
    public int deletePersonnelByIds(String ids) {
        Long[] personnelIds = Convert.toLongArray(ids);
        return personnelMapper.deletePersonnelByIds(personnelIds);
    }

    @Override
    public int changeStatus(ExaminePersonnelEntity personnel) {
        UpdateWrapper<ExaminePersonnelEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", personnel.getPersonnelId());
        return personnelMapper.update(personnel, wrapper);
    }

    @Override
    public int updatePersonnel(ExaminePersonnelEntity personnel) {
        return personnelMapper.updateById(personnel);
    }

    @Override
    public String checkPersonnelNameUnique(String examPersonnel) {
        int count = personnelMapper.checkPersonnelNameUnique(examPersonnel);
        if (count > 0) {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    @Override
    public int insertPersonnel(ExaminePersonnelEntity personnel) {
        return personnelMapper.insert(personnel);
    }

    @Override
    public void export(ExaminePersonnelEntity personnel, HttpServletResponse response) {
        QueryWrapper<ExaminePersonnelEntity> wrapper = new QueryWrapper<>();
        String personnelCategory = personnel.getPersonnelCategory();
        if (StrUtil.isNotEmpty(personnelCategory)) {
            wrapper.eq("personnel_category", personnel.getPersonnelCategory());
            wrapper.eq("attend", "1");
        }
        List<ExaminePersonnelEntity> data = personnelMapper.selectList(wrapper);

        Stream.iterate(0, i -> i + 1).limit(data.size()).forEach(index -> {
            ExaminePersonnelEntity personnelEntity = data.get(index);
            personnelEntity.setSerialNum(index + 1);
            personnelEntity.setBirthday(LocalDate.parse(personnelEntity.getBirthday()).format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        });

        String examTime = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月"));
        Map<String, Object> header = new HashMap<>(2);
        header.put("personnelCategory", personnelCategory);
        header.put("examTime", examTime);
        try {
            String exportName = examTime + "_" + personnelCategory + "_体能训练输入表";
            String template = "template/importTemplate.xlsx";
            ExcelUtil.writeExcelByTemplate(response, template, data, exportName, header, ExaminePersonnelEntity.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据异常");
        }
    }

    @Override
    public ExaminePersonnelEntity selectPersonnelById(Integer personnelId) {
        return personnelMapper.selectById(personnelId);
    }

    /**
     * 导入考核人员数据
     *
     * @param personnelList 考核人员数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importPersonnel(List<ExaminePersonnelEntity> personnelList, boolean isUpdateSupport) {
        if (StringUtils.isNull(personnelList) || personnelList.size() == 0) {
            throw new BusinessException("导入考核人员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        for (ExaminePersonnelEntity personnel : personnelList) {
            try {
                // 验证是否存在这个考核人员
                QueryWrapper<ExaminePersonnelEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("exam_personnel",personnel.getExamPersonnel());
                wrapper.eq("personnel_category",personnel.getPersonnelCategory());
                ExaminePersonnelEntity p = personnelMapper.selectOne(wrapper);
                if (StringUtils.isNull(p)) {
                    personnel.setCreateBy(operName);
                    this.insertPersonnel(personnel);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、考核人员 ").append(personnel.getExamPersonnel()).append(" 导入成功");
                } else if (isUpdateSupport) {
                    personnel.setUpdateBy(operName);
                    this.updatePersonnel(personnel);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、考核人员 ").append(personnel.getExamPersonnel()).append(" 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、账考核人员号 ").append(personnel.getExamPersonnel()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、考核人员 " + personnel.getExamPersonnel() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
